package com.lbiuse.wx.api;

import com.lbiuse.wx.util.WxHttpUtils;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;


/**
 * 
 * @author lupeng
 */
public class URLAPI {

	private static Logger logger = Logger.getLogger(QrcodeAPI.class);

	private static final String SHORT_URL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";

	/**
	 * 长链接转短链接
	 * 
	 * @param appId
	 * @param
	 * @return
	 */
	public static String toShort(String appId, String longUrl) {
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("长链接转短链接失败, 获取AccessToken失败!");
			return null;
		}
		String url = SHORT_URL.replace("ACCESS_TOKEN", token);
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("action", "long2short");
			jsonObject.put("long_url", longUrl);
			String json = jsonObject.toString();
			json = WxHttpUtils.post(url, json);
			jsonObject = JSONObject.fromObject(json);
			if (jsonObject.containsKey("errcode")) {
				int errcode = jsonObject.getInt("errcode");
				if (errcode != 0) {
					logger.error("长链接转短链接失败，错误码：" + errcode);
					return null;
				}
			}
			return jsonObject.getString("short_url");
		} catch (Exception e) {
			logger.error("长链接转短链接失败, 错误信息:" + e.getMessage());
			return null;
		}
	}

}
